    #include "mainwidget.h"
#include "./ui_mainwidget.h"
#include "debug.h"
#include "selfinfowidget.h"
#include "sessiondetailwidget.h"
#include "groupsessiondetailwidget.h"
#include "addfriendwidget.h"
#include "addfriendorcreatesessionwidget.h"
#include "sessionfriendarea.h"
#include "model/datacenter.h"

MainWidget * MainWidget::instance = nullptr;

MainWidget * MainWidget::getInstance()
{
    if (instance == nullptr)
    {
        instance = new MainWidget();
    }
    return instance;
}

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    this->setWindowTitle("我的鸡圈");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));

    // 初始化主窗口样式布局
    initMainWindow();
    // 初始化左侧窗口布局
    initLeftWindow();
    // 初始化右侧窗口布局
    initRightWindow();
    // 初始化中间窗口布局
    initMidWindow();

    initSignalSlot();
}

void MainWidget::initMainWindow()
{
    // 添加水平布局管理器
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setSpacing(0);                  // 设置内部元素间隔
    layout->setContentsMargins(0, 0, 0, 0); // 元素距离四个边界的间距
    this->setLayout(layout);

    _windowLeft = new QWidget();
    _windowMid = new QWidget();
    _windowRight = new QWidget();

    _windowLeft->setFixedWidth(70);
    // _windowMid->setMinimumWidth(150);
    // _windowMid->setMaximumWidth(300);
    _windowMid->setFixedWidth(250);
    _windowRight->setMinimumWidth(800);

    _windowLeft->setStyleSheet("QWidget { background-color: rgb(46, 46, 46); }");
    _windowMid->setStyleSheet("QWidget { background-color: rgb(247, 247, 247); }");
    _windowRight->setStyleSheet("QWidget { background-color: rgb(225, 225, 225); }");

    layout->addWidget(_windowLeft);
    layout->addWidget(_windowMid);
    layout->addWidget(_windowRight);
}

void MainWidget::initLeftWindow()
{
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setSpacing(20);
    layout->setContentsMargins(0, 20, 0, 0);
    _windowLeft->setLayout(layout);

    // 添加用户头像
    _userAvatar = new QPushButton();
    _userAvatar->setFixedSize(45, 45);
    _userAvatar->setIconSize(QSize(33, 33));
    // _userAvatar->setIcon(QIcon(":/resource/image/defaultAvatar.png"));
    _userAvatar->setStyleSheet("QPushButton { background-color: transparent; }");
    layout->addWidget(_userAvatar, 1, Qt::AlignTop | Qt::AlignHCenter);

    // 添加会话标签页按钮
    _sessionTaB = new QPushButton();
    _sessionTaB->setFixedSize(45, 45);
    _sessionTaB->setIconSize(QSize(33, 33));
    _sessionTaB->setIcon(QIcon(":/resource/image/session_active.png"));
    _sessionTaB->setStyleSheet("QPushButton { background-color: transparent; }");
    layout->addWidget(_sessionTaB, 1, Qt::AlignTop | Qt::AlignHCenter);

    // 添加好友标签页按钮
    _friendTaB = new QPushButton();
    _friendTaB->setFixedSize(45, 45);
    _friendTaB->setIconSize(QSize(33, 33));
    _friendTaB->setIcon(QIcon(":/resource/image/friend_inactive.png"));
    _friendTaB->setStyleSheet("QPushButton { background-color: transparent; }");
    layout->addWidget(_friendTaB, 1, Qt::AlignTop | Qt::AlignHCenter);

    // 添加申请标签页按钮
    _applyTaB = new QPushButton();
    _applyTaB->setFixedSize(45, 45);
    _applyTaB->setIconSize(QSize(33, 33));
    _applyTaB->setIcon(QIcon(":/resource/image/apply_inactive.png"));
    _applyTaB->setStyleSheet("QPushButton { background-color: transparent; }");
    layout->addWidget(_applyTaB, 1, Qt::AlignTop | Qt::AlignHCenter);

    layout->addStretch(20);
}

void MainWidget::initRightWindow()
{
    // 垂直布局管理器
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    _windowRight->setLayout(vlayout);

    // 创建上方标题栏
    _titleWidget = new QWidget();
    _titleWidget->setFixedHeight(62);
    _titleWidget->setObjectName("titleWidget");
    _titleWidget->setStyleSheet("#titleWidget { border-bottom: 1px solid rgb(200, 200, 200); border-left: 1px solid rgb(200, 200, 200); }");
    _titleWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    vlayout->addWidget(_titleWidget);

    // 给标题栏添加标题label和一个按钮
    QHBoxLayout *hlayout = new QHBoxLayout();
    hlayout->setSpacing(0);
    hlayout->setContentsMargins(10, 0, 10, 0);
    _titleWidget->setLayout(hlayout);

    _sessionTitleLabel = new QLabel();
    _sessionTitleLabel->setStyleSheet("QLabel { font-size: 22px; border-bottom: 1px solid rgb(200, 200, 200); }");
#if TEST_UI
    // 测试标题
    _sessionTitleLabel->setText("会话标题");
#endif
    hlayout->addWidget(_sessionTitleLabel);

    _extraBtn = new QPushButton();
    _extraBtn->setFixedSize(QSize(30, 30));
    _extraBtn->setIconSize(QSize(30, 30));
    _extraBtn->setIcon(QIcon(":/resource/image/more.png"));
    _extraBtn->setStyleSheet("QPushButton { border:none; background-color: transparent; } QPushButton:pressed { background-color: rgb(200, 200, 200) }");
    hlayout->addWidget(_extraBtn);

    // 添加消息展示区
    _msgShowArea = new MsgShowArea();
    vlayout->addWidget(_msgShowArea);
    // 添加消息编辑区: 确保处于下方
    _msgEditArea = new MsgEditArea();
    vlayout->addWidget(_msgEditArea, 0, Qt::AlignBottom);
}

void MainWidget::initMidWindow()
{
    QGridLayout *layout = new QGridLayout();  // 网格布局
    layout->setContentsMargins(0, 20, 0, 0);
    layout->setHorizontalSpacing(0);
    layout->setVerticalSpacing(10);
    _windowMid->setLayout(layout);

    _searchEdit = new QLineEdit();
    _searchEdit->setFixedHeight(30);
    _searchEdit->setPlaceholderText("搜索");
    _searchEdit->setStyleSheet("QLineEdit { border-radius: 5px; background-color: rgb(226, 226, 226); padding-left: 5px; }");

    _addBtn = new QPushButton();
    _addBtn->setFixedSize(30, 30);
    _addBtn->setIcon(QIcon(":/resource/image/cross.png"));
    QString style = "QPushButton { border-radius: 5px; background-color: rgb(226, 226, 226); }";
    style += "QPushButton:pressed { background-color: rgb(240, 240, 240); }";
    _addBtn->setStyleSheet(style);

    _sessionFriendArea = new SessionFriendArea();

    // 为了灵活地控制边距, 创建一些空白区域
    QWidget *space1 = new QWidget();
    space1->setFixedWidth(5);
    QWidget *space2 = new QWidget();
    space2->setFixedWidth(10);
    QWidget *space3 = new QWidget();
    space3->setFixedWidth(10);

    layout->addWidget(space1, 0, 0);
    layout->addWidget(_searchEdit, 0, 1);
    layout->addWidget(space2, 0, 2);
    layout->addWidget(_addBtn, 0, 3);
    layout->addWidget(space3, 0, 4);

    layout->addWidget(_sessionFriendArea, 1, 0, 1, 5); // 第1行, 第0列, 跨1行, 跨5列
}

void MainWidget::initSignalSlot()
{
    model::DataCenter *dataCenter = model::DataCenter::getInstance();

    // 连接信号槽, 处理标签页按钮切换的问题
    connect(_sessionTaB, &QPushButton::clicked, this, &MainWidget::switchTabToSession);
    connect(_friendTaB, &QPushButton::clicked, this, &MainWidget::switchTabToFriend);
    connect(_applyTaB, &QPushButton::clicked, this, &MainWidget::switchTabToApply);

    // 点击自身头像出现信息
    connect(_userAvatar, &QPushButton::clicked, this, [=](){
        SelfInfoWidget *selfInfoWidget = new SelfInfoWidget(this);
        selfInfoWidget->exec();
    });

    // 点击会话详情按钮
    connect(_extraBtn, &QPushButton::clicked, this, [=](){
        bool isSingleChat = true;
        if (isSingleChat)
        {
            SessionDetailWidget *sessionDetailWidget = new SessionDetailWidget(this);
            sessionDetailWidget->exec();
        }
        else
        {
            GroupSessionDetailWidget *groupSessionDetailWidget = new GroupSessionDetailWidget(this);
            groupSessionDetailWidget->exec();
        }
    });

    // 点击添加好友按钮
    connect(_addBtn, &QPushButton::clicked, this, [=](){
        AddFriendOrCreateSessionWidget *addFriendOrCreatesessionWidget = new AddFriendOrCreateSessionWidget(this);
        addFriendOrCreatesessionWidget->exec();
    });

    // 点击搜索框
    connect(_searchEdit, &QLineEdit::returnPressed, this, [=](){
        AddFriendWidget *addFriendWidget = new AddFriendWidget(this);
        addFriendWidget->setSearchKey(_searchEdit->text());
        _searchEdit->setText("");
        addFriendWidget->exec();
    });

    // 获取个人信息
    connect(dataCenter, &model::DataCenter::getMyselfDone, this, [=](){
        auto myself = dataCenter->getMyself();
        _userAvatar->setIcon(myself->_avatar);
    });
    dataCenter->getMyselfAsync();

    // 获取好友列表
    loadFriendList();

    // 获取会话列表
    loadSessionList();

    // 获取申请列表
    loadApplyList();
}

void MainWidget::switchTabToSession()
{
    if (_activeTaB == SESSION_LIST) return;
    _activeTaB = SESSION_LIST;
    _sessionTaB->setIcon(QIcon(":/resource/image/session_active.png"));
    _friendTaB->setIcon(QIcon(":/resource/image/friend_inactive.png"));
    _applyTaB->setIcon(QIcon(":/resource/image/apply_inactive.png"));

    // 加载出会话列表
    loadSessionList();
}

void MainWidget::switchTabToFriend()
{
    if (_activeTaB == FRIEND_LIST) return;
    _activeTaB = FRIEND_LIST;
    _sessionTaB->setIcon(QIcon(":/resource/image/session_inactive.png"));
    _friendTaB->setIcon(QIcon(":/resource/image/friend_active.png"));
    _applyTaB->setIcon(QIcon(":/resource/image/apply_inactive.png"));

    // 加载出好友列表
    loadFriendList();
}

void MainWidget::switchTabToApply()
{
    if (_activeTaB == APPLY_LIST) return;
    _activeTaB = APPLY_LIST;
    _sessionTaB->setIcon(QIcon(":/resource/image/session_inactive.png"));
    _friendTaB->setIcon(QIcon(":/resource/image/friend_inactive.png"));
    _applyTaB->setIcon(QIcon(":/resource/image/apply_active.png"));

    // 加载出好友申请列表
    loadApplyList();
}

void MainWidget::loadSessionList()
{
    // 先判断datacenter中是否有数据
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto chatSessionList = dataCenter->getChatSessionList();
    if (chatSessionList != nullptr)
    {
        DEBUG() << "加载本地会话列表";
        updateChatSessionList();
    }
    else
    {
        DEBUG() << "从服务器加载会话列表";
        connect(dataCenter, &model::DataCenter::getChatSessionListDone, this, &MainWidget::updateChatSessionList, Qt::UniqueConnection);
        dataCenter->getChatSessionListAsync();
    }
}

void MainWidget::loadFriendList()
{
    // 先判断datacenter中是否有数据
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto friendList = dataCenter->getFriendList();
    if (friendList != nullptr)
    {
        DEBUG() << "加载本地好友列表";
        updateFriendList();
    }
    else
    {
        DEBUG() << "从服务器加载好友列表";
        connect(dataCenter, &model::DataCenter::getFriendListDone, this, &MainWidget::updateFriendList, Qt::UniqueConnection);
        dataCenter->getFriendListAsync();
    }
}

void MainWidget::loadApplyList()
{
    // 先判断datacenter中是否有数据
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto applyList = dataCenter->getApplyList();
    if (applyList != nullptr)
    {
        DEBUG() << "加载本地申请列表";
        updateApplyList();
    }
    else
    {
        DEBUG() << "从服务器加载申请列表";
        connect(dataCenter, &model::DataCenter::getApplyListDone, this, &MainWidget::updateApplyList, Qt::UniqueConnection);
        dataCenter->getApplyListAsync();
    }
}

void MainWidget::loadRecentMessage(const QString &chatSessionId)
{
    // 先判断datacenter中是否有数据
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    if (dataCenter->getRecentMsg(chatSessionId) != nullptr)
    {
        DEBUG() << "加载本地最近消息";
        updateRecentMsg(chatSessionId);
    }
    else
    {
        DEBUG() << "从服务器加载最近消息";
        connect(dataCenter, &model::DataCenter::getRecentMsgDone, this, &MainWidget::updateRecentMsg, Qt::UniqueConnection);
        dataCenter->getRecentMsgAsync(chatSessionId);
    }
}

void MainWidget::updateFriendList()
{
    if (_activeTaB != FRIEND_LIST) return;

    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto friendList = dataCenter->getFriendList();
    // 清空之前界面的数据
    _sessionFriendArea->clear();
    // 遍历好友列表, 添加到界面中
    for (auto &f : *friendList)
    {
        _sessionFriendArea->addItem(Friend, f._user_id, f._avatar, f._nickname, f._desciption);
    }
}

void MainWidget::updateChatSessionList()
{
    if (_activeTaB != SESSION_LIST) return;

    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto chatSessionList = dataCenter->getChatSessionList();
    // 清空之前界面的数据
    _sessionFriendArea->clear();
    // 遍历好友列表, 添加到界面中
    for (auto &c : *chatSessionList)
    {
        QString msg;
        if (c._last_message._message_type == model::STRING_TYPE)
            msg = c._last_message._content;
        else if (c._last_message._message_type == model::IMAGE_TYPE)
            msg = "[图片]";
        else if (c._last_message._message_type == model::FILE_TYPE)
            msg = "[文件]";
        else if (c._last_message._message_type == model::SPEECH_TYPE)
            msg = "[语音]";
        else
        {
            ERROR() << "错误消息类型 message_type: " << c._last_message._message_type;
            continue;
        }
        _sessionFriendArea->addItem(Session, c._chat_session_id, c._avatar, c._chat_session_name, msg);
    }
}

void MainWidget::updateApplyList()
{
    if (_activeTaB != APPLY_LIST) return;

    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto applyList = dataCenter->getApplyList();
    // 清空之前界面的数据
    _sessionFriendArea->clear();
    // 遍历好友列表, 添加到界面中
    for (auto &f : *applyList)
    {
        _sessionFriendArea->addItem(Apply, f._user_id, f._avatar, f._nickname, f._desciption);
    }
}

void MainWidget::updateRecentMsg(const QString &chatSessionId)
{
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    auto* recentMsgs = dataCenter->getRecentMsg(chatSessionId);
    // 清空之前的会话数据
    _msgShowArea->clear();
    for (auto &msg : *recentMsgs)
    {
        bool isLeft = msg._sender._user_id != dataCenter->getMyself()->_user_id;
        _msgShowArea->addMsg(isLeft, msg);
    }

    // 设置会话标题
    model::ChatSessionInfo *chatSessionInfo = dataCenter->findChatSessionById(chatSessionId);
    if (chatSessionInfo != nullptr)
        _sessionTitleLabel->setText(chatSessionInfo->_chat_session_name);

    // 保存当前选中的会话
    dataCenter->setCurrentChatSessionId(chatSessionId);

    // 自动将滚动条滚动到末尾
    _msgShowArea->scrollToEnd();
}

void MainWidget::switchToSession(const QString &friendId)
{
    DEBUG() << "切换到对应的会话: friendId: " << friendId;
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    model::ChatSessionInfo *chatSessionInfo = dataCenter->findChatSessionByUserId(friendId);
    if (chatSessionInfo == nullptr)
    {
        CRITICAL() << "当前选中的好友, 对应的会话不存在";
        return;
    }
    // 把选中的会话置顶
    dataCenter->topChatSessionInfo(*chatSessionInfo);
    // 切换到会话标签页
    switchTabToSession();
    // 加载对应历史消息
    _sessionFriendArea->clickItem(0);
}

MainWidget::~MainWidget()
{
    delete ui;
}
